<?php

namespace App\Listeners;


use App\Events\Event;
use App\Events\CourseEvent;
use App\Events\ScheduleEvent;
use App\Model\Eeoapi\Eeocourse;
use App\Model\System\Eeolog;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;


class Listener
{
    protected $uri;
    protected $request;
    protected $response;


    public function dataMaker()
    {
        $org = Event::getOrg();
        $data = array(
            "SID" => $org['SID'],
            "safeKey" => $org['safeKey'],
            "timeStamp"=> $org['timeStamp'],
        );
        return $data;
    }

    public function getRootid()
    {
        $org = Event::getOrg();
        return $org['rootid'];
    }

    /**
     * @param $uri
     */
    public function setUri($uri)
    {
        $org = Event::getOrg();
        $this->uri = $org['eeourl'] . $uri;
    }

    /**
     * @param $uri
     */
    public function setCloudUri($uri)
    {
        $org = Event::getOrg();
        $this->uri = $org['eeocloudurl'] . $uri;
    }


    /**
     * @param $data
     */
    public function setRequest($data)
    {
        $this->request = $data;
    }


    /**
     * @param $data
     */
    public function setResponse($data)
    {
        $this->response = $data;
    }

    /**
     * 检测文件路径是否存在，检测php版本信息，返回文件对象或字符串
     * @param $path
     * @return \CURLFile|string
     */
    public function uploadCheck($path)
    {
        if($path){
            if(version_compare(PHP_VERSION, '5.5.0') >= 0)
                $cfile = new \CURLFile($path);
            else
                $cfile = '@'.$path;
        }else{
            $cfile = '';
        }
        return $cfile;
    }

    /**
     * 注册用户
     * @param $telephone
     * @param $nickname
     * @return true
     * @throws  \Exception
     */
    public function register($telephone,$nickname,$password)
    {
        try{
            $org = Event::getOrg();
            if(!$password)
            $password = $org['registerDefaultPwd'];
            $this->setUri('register');
            $data = $this->dataMaker();
            $data["telephone"] = $telephone;
            $data["nickname"] = $nickname;
            $data["md5pass"] = md5($password);
            $this->setRequest($data);
            $result = $this->callEeoApi();
            if($result['error_info']['errno'] === 1 || $result['error_info']['errno'] === 135 ) {
                return true;
            }else{
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }

    }

    /**
     * 查询直播/回放链接
     * @param $event
     */
    function getWebcast($event,$courseId,$classId)
    {
        try{
            $this->setUri('getWebcastUrl');
            $data = $this->dataMaker();
            $data["courseId"] = $courseId;
            if($classId)
            $data["classId"] = $classId;
            $this->setRequest($data);
            $result = $this->callEeoApi();
            if($result['error_info']['errno'] == 1) {
                $event->setWebcast($result['data']);
            }
            else{
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }


    /**
     * 修改用户昵称
     * @param $event
     */
    protected function editUser($telephone,$name)
    {
        try{
            $this->setUri('editUserInfo');
            $data = $this->dataMaker();
            $data["telephone"] = $telephone;
            $data["nickname"] = $name;
            $this->setRequest($data);
            $result = $this->callEeoApi();
            $code = $result['error_info']['errno'];
            if(!in_array($code,[1,192]) ) {
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
            return true;
        }catch (\Exception $e){
            throw $e;
        }
    }


    /**
     * 保存调用日志
     */
    function __destruct()
    {

    }


    /**
     * 调用eeo api
     * @return mixed|string
     * @throws \Exception
     */
    public function callEeoApi()
    {
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $this->uri );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $this->request );
        $response = curl_exec($ch);
        $this->setResponse($response);
        if (curl_errno($ch)) {
            throw  new  \Exception(curl_error($ch), 2);
        }
        curl_close($ch);

        $response = trim($response);
	
        $obj = new Eeolog();
        $obj->synctime = date('Y-m-d H:i:s');
        $obj->invokeurl = $this->uri;
        $obj->returndata = $this->response;
        $obj->invokeparms = json_encode($this->request);
        $obj->save();
	
        if(!$response){
            throw  new  \Exception('EEO API 调用失败', 2);
        }
        $response = json_decode($response,JSON_UNESCAPED_UNICODE);
        return $response;
    }



}
